import React, {useEffect, useRef, useState} from "react";
import type {Option} from "artplayer/types/option";
import Artplayer from "artplayer";
import {createStyles} from "antd-style";
import {useMessageApiStore, useVideoIndexStore} from "@/store/BaseStore.ts";
import {getVideoTitle} from "@/api/VideoApi.ts";

const useStyle = createStyles(({css, token}) => {
    return {
        videoContainer: css`
            width: 100vw;
            height: 40vh;
            display: block;
            .controller-btn {
                height: 100%;
                padding: 0 20px;
                font-size: 20px;
                font-weight: 500;
                border: none;
                transition: font-size .2s;
                background-color: transparent;
                &:hover {
                    font-size: 22px;
                }
            }
            .video-title {
                font-size: 15px;
                line-height: 1;
                white-space: nowrap;
                width: auto;
                height: auto;
                padding: 5px 0;
                overflow-x: hidden;
            }
            .art-bottom-fullscreen {
                padding: 0 100px;
            }
        `,
    }
})

/**
 * 通过视频容器id和视频id获取视频链接
 */
const getVideUrl = (videoContainerIndex: number, videoIndex: number) => {
    return '/api/video/' + videoContainerIndex + '/' + videoIndex;
}

document.addEventListener('fullscreenchange', (event) => {
    if (document.fullscreenElement != null) {
        // 全屏
    }
})

let videoContainerSize: number;

let art: Artplayer | null;

const VideoPlayer: React.FC = () => {
    const player = useRef<HTMLDivElement>();
    const vci = useVideoIndexStore(state => state.videoContainerIndex);
    const vi = useVideoIndexStore(state => state.videoIndex);
    const setter = useVideoIndexStore(state => state.set);
    const _next = useVideoIndexStore(state => state.next);
    const _pre = useVideoIndexStore(state => state.pre)
    const _videoContainerSize = useVideoIndexStore(state => state.videoContainerSize);
    if (_videoContainerSize != undefined) {
        videoContainerSize = _videoContainerSize;
    }

    const {styles} = useStyle();

    const messageApi = useMessageApiStore(state => state.messageApi);

    const pre = () => {
        if (!_pre()) {
            messageApi.info("已经是第一个了")
        }
    }

    const next = () => {
        if (!_next()) {
            messageApi.info("已经是最后一个了")
        }
    }

    const updateTitle = (art: Artplayer) => {
        // @ts-ignore
        getVideoTitle(art.vci, art.vi).then((data) => {
            art.controls.update({
                name: 'title',
                index: 14,
                position: 'top',
                html: `<h3 class="video-title">${data.data.data}</h3>`
            })
        })
    }

    useEffect(() => {
        const p = player.current

        const option: Option = {
            container: p,
            url: getVideUrl(vci, vi),
            volume: 0.5,
            lang: 'zh-cn',
            autoplay: false,
            controls: [
                {
                    name: 'fullscreen',
                    index: 10,
                    position: "right",
                    html: `<button class="controller-btn">全屏</button>`,
                    click: () => {
                        art.fullscreen = !art.fullscreen
                    }
                },
                {
                    name: 'pre',
                    index: 11,
                    position: 'left',
                    html: `<button class="controller-btn">⫷</button>`,
                    click: pre,
                },
                {
                    name: 'next',
                    index: 12,
                    position: 'left',
                    html: `<button class="controller-btn">⫸</button>`,
                    click: next,
                },
                {
                    name: 'randomNext',
                    index: 13,
                    position: 'left',
                    html: `<button class="controller-btn">⅓</button>`,
                    click: () => {
                        setter(vci, Math.floor(Math.random() * videoContainerSize), videoContainerSize)
                        art.switchUrl(getVideUrl(vci, vi))
                    }
                },
                {
                    name: 'title',
                    index: 14,
                    position: 'top',
                    html: `<h3></h3>`
                },
            ]
        }

        if (art == null) {
            art = new Artplayer(option)

            art.layers.show = false

            art.on("fullscreen", () => {
                const bottom = document.querySelector(".art-bottom");
                if (art.fullscreen) {
                    bottom.classList.add("art-bottom-fullscreen")
                } else {
                    bottom.classList.remove("art-bottom-fullscreen")
                }
            })

            art.on("ready", () => {
                updateTitle(art);
            })

            art.on("restart", () => {
                updateTitle(art);
            })

            // 自动连播
            art.on("video:ended", () => {
                if (vi + 1 >= videoContainerSize) {
                    messageApi.info("已经是最后一个了")
                } else {
                    setter(vci, vi + 1, videoContainerSize)
                }
            })

            // 设置长按倍速播放
            let timer = null;
            const faster = () => {
                timer = setTimeout(() => {
                    art.playbackRate = 3
                }, 500)
            }
            const defaster = () => {
                clearTimeout(timer)
                art.playbackRate = 1
            }

            p.addEventListener("touchstart", faster)
            p.addEventListener("touchend", defaster)
        } else {
            art.switchUrl(getVideUrl(vci, vi))
        }
        // @ts-ignore
        art.vi = vi
        // @ts-ignore
        art.vci = vci
    }, [vci, vi]);

    useEffect(() => {
        // 防止开发过程中，修改代码后重复挂在播放器，实际使用时没有区别
        return () => {
            if (art && art.destroy) {
                art.destroy()
            }
        }
    }, []);

    return (
        <div>
            <div className={styles.videoContainer} ref={player}>
                播放器错误，请重试
            </div>
        </div>
    )
}

export default VideoPlayer;
